<?php

class Store extends Controller {

	function index()
	{
	
	$this->load->model('Store_model');
	
		
	//$this->output->cache(5);
	
	  $this->load->helper('file');
      $this->load->helper('date');
      $this->load->helper('url');
	
	$data['title']= "Rybalka.com.ua — интернет-магазин рыболовных снастей";
	
	$row1 = $this->db->query("SELECT id,title,link, name FROM store WHERE level=1 AND folder=1 ORDER BY list");
	$data['row1'] = $row1;
	
	$this->load->view('global/top', $data);
	$this->load->view('store/menu');
	$this->load->view('store/catalog_level0', $data);
	$this->load->view('global/bottom');
	}



		function catalog($level1, $level2, $level3, $level4)
		{
		//$this->output->cache(3);
		
		$this->load->model('Store_model');
		$this->load->library('pagination');

      	$this->load->helper('file');
      	$this->load->helper('date');
      	$this->load->helper('url');


					if(isset ($level1)){ //Первый уровень

								if(isset ($level2)){ //Второй уровень

										if(isset ($level3)){ //Третий уровень

													if(isset ($level4)){ //Четвертый уровень

												$data['level1']=$level1;
    											$data['level2']=$level2;
    											$data['level3']=$level3;
    											$data['level4']=$level4;

						                    $query = $this->db->query("SELECT * FROM store WHERE id='$level4' AND available=1 LIMIT 1");
						    				$data['row'] = $query->row();
						    				
						    				
						    				if($query->num_rows == '0')
						    				{
						    				
						    					show_404('page');
						    				}

											$row = $query->row();
											$data['title'] = $row->title;
										

    										   	 		$this->load->view('global/top', $data);
    										   	 		$this->load->view('store/menu', $data);

    										   	 		$this->load->view('store/catalog_level4', $data);

    										   	 		$this->load->view('global/bottom');


													}else{ //Если только третий уровень

    											 		$data['level1']=$level1;
    											 		$data['level2']=$level2;
    											 		$data['level3']=$level3;


    											 	   //Определяем Титл
    											 		$query = $this->db->query("SELECT title  FROM store WHERE level=3 AND link='$level3' AND father=(SELECT id FROM store WHERE level=2 AND link='$level2' AND father=(SELECT id FROM store WHERE level=1 and link='$level1')) LIMIT 1 ");
    										   	  $row = $query->row();
    										   	  $data['title']=$row->title;


                               	//Все продукты в данной папке
    										   	   	$data['query'] = $this->db->query("SELECT * FROM store WHERE level=4 AND available=1 AND folder=0 AND father=(SELECT id  FROM store WHERE level=3 AND link='$level3' AND father=(SELECT id FROM store WHERE level=2 AND link='$level2' AND father=(SELECT id FROM store WHERE level=1 and link='$level1'))) ORDER BY name");

    										   	 		$this->load->view('global/top', $data);
    										   	 		$this->load->view('store/menu', $data);

    										   	 		$this->load->view('store/catalog_level3', $data);

    										   	 		$this->load->view('global/bottom');
													}


										}else{ //Если только второй уровень

											 $data['level1']=$level1;
											 $data['level2']=$level2;

											//Находим все товары в подкатегориях

											$all=array();

												$level3 = $this->db->query("SELECT id,title FROM store where father=(SELECT id FROM store WHERE link='$level2' and father=(SELECT id FROM store WHERE link='$level1')) AND level=3 ORDER BY name");
					                            foreach ($level3->result() as $row3){
					                                  $level4 = $this->db->query("SELECT id FROM store where father='$row3->id' and level=4 AND available=1 order by name");
					                                        foreach ($level4->result() as $row4){
					                                            array_push($all, $row4->id);
					                                        }
					                            }

			                             //Делаем случайный порядок
			                             //shuffle($all);

			                 //Определяем Титл
    									$query = $this->db->query("SELECT title  FROM store WHERE level=2 AND link='$level2' AND father=(SELECT id FROM store WHERE level=1 AND link='$level1' ) LIMIT 1");
    									$row = $query->row();
    									$data['title']=$row->title;

					                    $data['all']=$all;

    								$this->load->view('global/top', $data);
    								$this->load->view('store/menu', $data);

    								$this->load->view('store/catalog_level2', $data);
  							
    								$this->load->view('global/bottom');
								}



									}else{ //Если только первый уровень
                    //$this->output->cache(5);
											$data['level1']=$level1;
                      
                      //Для таваров одного уровня
                      if( $level1=="shoes"){
                      $only=1;
                      }
                      
                      //Находим все товары в подкатегориях
                      if($only==1){
	                      $level2= $this->db->query("SELECT id,title,link, name FROM store WHERE level=2 AND folder=1 AND father=(SELECT id FROM store WHERE link='$level1')");
	                      $row2 = $level2->row();
	                      $data['level2']=$row2->link;
	                      
	                      $level3 = $this->db->query("SELECT id,link FROM store where father='$row2->id' and level=3");
	                      $row3 = $level3->row();
	                      $data['level3']=$row3->link;
	                      
	                      $data['query']= $this->db->query("SELECT * FROM store where father='$row3->id' and level=4 and available =1");
	                      $data['only'] = 1;
                                  
                      }else{
	                      $row2 = $this->db->query("SELECT id,title,link, name FROM store WHERE level=2 AND folder=1 AND father=(SELECT id FROM store WHERE link='$level1') ORDER BY list");
	                      $data['row2'] = $row2;
                      }
                     
                      
                    										
                      //Определяем Титл
    									$query = $this->db->query("SELECT title  FROM store WHERE level=1 AND link='$level1' LIMIT 1");
    									$row = $query->row();
    									$data['title']=$row->title;

                    

    								$this->load->view('global/top', $data);
    								$this->load->view('store/menu', $data);
                    
                    if($only != 1){
    								$this->load->view('store/catalog_level1', $data);
    							   }else{
                     $this->load->view('store/catalog_level3', $data);
                     }
    								$this->load->view('global/bottom');
									}


					}else{ 
					
					//Нулевой уровень
				         					
    					 $this->load->view('global/top');
    				  	 $this->load->view('store/menu');
    				  	 $this->load->view('store/catalog_level0');
    				   	 $this->load->view('global/bottom');
    				   	 
    				   	 
    				   	  
					}
					
				

		}
		



//Функции для работы с корзиной
		
			function add()
	    {
	      
	    
	    //Отменяем кеширование
		header("Cache-Control: no-cache, must-revalidate"); 
		header("Pragma: no-cache");       
	          
	     $session=$this->session->userdata('session_id');
	    	if($_POST){
             
              $articles=$_POST['id'];
                    
                    while(list($id,$quantity) = each($articles)){
                      
                      $quantity=1;

                            //А если такие товары уже есть у этой сессии? Проверяем и добавляем!!!
                            $query = $this->db->query("SELECT quantity FROM session_to_store WHERE session='$session' AND store='$id'");
                            
                            $price = $this->db->query("SELECT price FROM articles WHERE id='$id' LIMIT 1");
                            $price = $price->row();
                            $price = $price->price;
                            
                            global $dollar;
                            $price = $price * $dollar;
                            $price = round($price);
          								
							if ($query->num_rows() > 0){
                             $row = $query->row();
                              
                             $data['quantity']=$row->quantity + $quantity;
                             $this->db->update('session_to_store', $data, array('session' => $session, store=>$id)); 
                            
                            }else{
								
                               //Ну а если нет, заносим данные в таблицу session_to_store
                               $data['session']=$session;
                               $data['store']=$id;
                               $data['quantity']=$quantity;
                               $data['price']=$price;
                               $data['date']=mdate("%Y-%m-%d");
                               
                               $this->db->insert('session_to_store', $data); 
                            }

                     
                     
                    }
      }
	

	                
        $data['query'] = $this->db->query("SELECT * FROM session_to_store WHERE session='$session'");
        $data['title'] = 'Корзина';

        	$this->load->view('global/top', $data);
        	$this->load->view('store/menu');
      
          $this->load->view('store/add', $data);
        	$this->load->view('global/bottom');
	   }
	   
	   
	   
	   function del($id)
	   {
     $this->load->helper('url');
     $session=$this->session->userdata('session_id');

     $this->db->delete('session_to_store', array('id' => $id, 'session' => $session)); 
     
     redirect ('/store/add');

     }
     
     
     function buy($from)
     {
     $this->load->helper('url');
     $session=$this->session->userdata('session_id');
      
      //Отменяем кеширование
      header("Cache-Control: no-cache, must-revalidate"); 
      header("Pragma: no-cache"); 
     
        $buy=$_POST['id'];
        
        
           while(list($id,$value) = each($buy)){
              $value=intval($value);
              
              $query = $this->db->query("SELECT id FROM session_to_store WHERE session='$session' AND id='$id'");
          				    if ($query->num_rows() > 0){
                       $row = $query->row();
                       
                            if($value != 0){
                              $data['quantity']=$value;
                              $this->db->update('session_to_store', $data, array('session' => $session, id=>$row->id)); 
                            }
                            
                       }else{
                            redirect('/store/add');
                       }			
          }
          
          $data['query']=$this->db->query("SELECT * FROM session_to_store WHERE session='$session'");
          $data['from']=$from;
          $data['title']='Оформление заказа';
        
          $this->load->view('global/top', $data);
        	$this->load->view('store/menu');
      
          $this->load->view('store/buy', $data);
        	$this->load->view('global/bottom');
     }

      
     function save()
     {
      //Отменяем кеширование
      //header("Cache-Control: no-cache, must-revalidate"); 
     // header("Pragma: no-cache");   
     
     $this->load->helper('url');
     $this->load->helper('date');
     $this->load->library('validation');
     
     $session=$this->session->userdata('session_id');
     $username=$this->session->userdata('id');
     
      
              		//Check incoming variables
              	  $rules['login']	= "max_length[32]|trim";
                  $rules['name']	= "required|trim";
                  $rules['city']  = "trim";
                  $rules['phone']	= "required|trim";
                  $rules['adres']	= "required|trim";
                  $rules['index']	= "trim";	
                  $rules['comments']  = "trim";	
                  $rules['pay']	= "trim";
              
              		$this->validation->set_rules($rules);
              		
              		if ($this->validation->run() == false){
              		//Если валидация не прошла
              		
		                redirect("/store/buy");	
		                }else{
		                //Если валидация прошла успешно
		                
		                  $data['mail']= $this->validation->login;
              	     	$data['name']= $this->validation->name;
              	     	$data['city']= $this->validation->city;
              	     	$data['phone']= $this->validation->phone;
              	     	$data['index']= $this->validation->index;
              	     	$data['adres']= $this->validation->adres;
              	     	$data['comments']= $this->validation->comments;
              	     	$data['pay']= $this->validation->pay;
              	     	$data['session']= $session;
              	     	$data['username']= $username;
              	     	$data['date']= mdate("%Y-%m-%d");
              	     	
                     $query=$this->db->query("SELECT id FROM purchase WHERE session='$session' AND username='$username'");
                     if($query->num_rows === 0){
                     
                       $this->db->insert('purchase', $data);
                       
                       
                       
                        $query=$this->db->query("SELECT id FROM session_to_store WHERE session='$session' AND status=0");
                          
                        if($query->num_rows > 0){  
                            foreach ($query->result() as $add){
                                $up['status']=1; 
                                $this->db->where('id', $add->id);
  			                        $this->db->update('session_to_store', $up);
                            }
                          } 
                        

              	      $query=$this->db->query("SELECT MAX(id) AS id FROM purchase LIMIT 1");
                      $row = $query->row();
                      
                      $number=$row->id;
                      $data['number']=$row->id;
                      $data['date']= mdate("%d.%m.%Y");
                      $data['title'] = 'Уведомление';
                      
                      
                     //Подчитываем общую стоимость
                      $articles = $this->db->query("SELECT price,quantity FROM session_to_store WHERE session ='$session'");
    				             
                        foreach ($articles->result() as $articles){
    				         $summ=($articles->price * $articles->quantity) + $summ;
    				     }
                    
            
                     
                      $data['summ']=$summ;
                      
                    $this->load->view('global/top', $data);
                   	$this->load->view('store/menu');
                  
                    $this->load->view('store/save', $data);
                    $this->load->view('global/bottom');
                      
          	     	
	                   }else{
                     redirect("/store/");	
                     }
                     

		              }

     
     }
     
     
     
function account($number)
{

      header("Cache-Control: no-cache, must-revalidate"); 
      header("Pragma: no-cache");


    if(!isset($number)){
    exit;
    }
    
    $session=$this->session->userdata('session_id');
    
    $if_session = $this->db->query("SELECT id FROM purchase WHERE session ='$session' AND id='$number' LIMIT 1");
   
    if($if_session->num_rows == 0){
    exit;
    }
    
    $purchase = $this->db->query("SELECT * FROM purchase WHERE session ='$session' AND id='$number' LIMIT 1");
    $data['purchase'] = $purchase->row();
    
    $date = $this->db->query("SELECT YEAR(date) AS year, DATE_FORMAT(date, '%m') AS month, DATE_FORMAT(date, '%d') AS day FROM purchase WHERE session ='$session' AND id='$number' LIMIT 1");
    $data['date'] = $date->row();
    
    $this->load->view('store/account', $data);


} 


function delivery(){

                $data['title']="Доставка и оплата";

                     $this->load->view('global/top', $data);
                    	$this->load->view('store/menu');
                  
                      $this->load->view('store/delivery');
                    	$this->load->view('global/bottom');
}




    function search($s){
    $this->load->model('Store_model');
    
    $data['s']=$s;
    $data['search']="false";
    $data['title']="Результаты поиска";
    
    $this->load->view('global/top', $data);
    $this->load->view('store/menu');
    $this->load->view('store/search', $data);
    
    $this->load->view('global/bottom');
    }


}
?>